<template>
	<view>
		<mvBar :mysNavConfig="mysNavConfig" @onLeftClick="onLeftClick"></mvBar>
		<view class="u-page">
			<u-toast ref="uToast"></u-toast>
			<view class="u-demo-block">
				<view class="u-demo-block__content">
					<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
					<u-form labelPosition="left" :model="equipmentForm" ref="form1">
						<u-form-item label="名称" borderBottom prop="name" ref="item1">
							<u-input border="none" v-model="equipmentForm.name" placeholder="请输入设备名称"></u-input>
						</u-form-item>
						<u-form-item label="简介" borderBottom prop="description" ref="item2">
							<u--textarea confirmType='done' placeholder="设备名称不能低于2个字"
								v-model="equipmentForm.description" maxlength="50" :count="true"></u--textarea>
						</u-form-item>
						<u-form-item label="图片" borderBottom prop="picUrl" ref="item3">
							<u-upload name="picUrl" :fileList="fileList" @afterRead="afterRead" @delete="deletePic"
								:previewFullImage="true" :maxCount="4" :multiple="true">
							</u-upload>
						</u-form-item>
					</u-form>

					<u-button type="primary" text="确定" customStyle="margin-top: 50px" @click="submit"></u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				mysNavConfig: {
					/* 占位开启  */
					navPadding: true,
					/* 背景 */
					bgColor: "#0055ff",
					/* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
					navTitle: {
						text: "修改设备",
						color: "#ffffff",
						fontSize: "20px", // px upx rpx
						fontWeight: "500", // 100 - 700
					},
					isCustomFn: true,
					btnType: "type2",
					type2Config: {
						// 左图标
						leftPath: "/static/img/back.png",
						// 右图标
						rightPath: "/static/img/home.png",
						// 圆角
						radius: "40rpx",
					}
				},
				userInfo: '',
				equipmentRealId: '',
				fileList: [],
				addlist: [],
				equipmentForm: {
					name: '',
					description: ''
				},
				rules: {
					'name': {
						type: 'string',
						required: true,
						max: 14,
						message: '设备名称不超过14个字',
						trigger: ['blur', 'change']
					},
					'description': {
						type: 'string',
						min: 2,
						max: 50,
						required: true,
						message: '设备描述不能低于2个字并且不能超过50个字',
						trigger: ['change']
					}
				}
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
		},
		onLoad(option) {
			this.userInfo = uni.getStorageSync('userInfo');
			this.equipmentRealId = option.equipmentRealId;
			this.getData(this.equipmentRealId);
		},
		methods: {
			getData(equipmentRealId) {
				uni.request({
					url: getApp().globalData.serverAddress + this.$uri.Uri_getEquipment.replace("{userRealId}",
							this.userInfo.userRealId)
						.replace("{equipmentRealId}", equipmentRealId),
					dataType: "json",
					method: "GET",
					success: (res) => {
						if (res.data.code == 0) {
							var result = res.data.data;
							this.equipmentForm.name = result.name;
							this.equipmentForm.description = result.description;
							if (result.picUrl[0] !== '') {
								for (var i = 0; i < result.picUrl.length; i++) {
									this.addlist.push({
										url: result.picUrl[i]
									})
									this.fileList.push({
										url: getApp().globalData.serverAddress + result.picUrl[i]
									});
								}
							}
						} else {
							this.$utils.showToast(this, res.data.msg, 'error', 1, '');
						}
					},
					fail: (res) => {
						this.$utils.showToast(this, res.data.msg, 'error', 1, '');
					}
				})
			},
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.addlist.splice(event.index, 1)
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: getApp().globalData.serverAddress + this.$uri
							.Uri_uploadImage, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
								var obj = JSON.parse(res.data);
								this.addlist.push({
									url: obj.data[0]
								})
							}, 1000)
						}
					});
				})
			},
			submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				let equipmentUpdateDto = new Object();
				equipmentUpdateDto.name = this.equipmentForm.name;
				equipmentUpdateDto.description = this.equipmentForm.description;
				equipmentUpdateDto.picUrl = '';
				if (this.addlist.length > 0) {
					var arrlis = []
					for (let item of this.addlist) {
						arrlis.push(item.url)
					}
					equipmentUpdateDto.picUrl = arrlis.join(",")
				}
				this.$refs.form1.validate().then(res => {
					uni.showLoading({
						title: "程序执行中...",
						mask: true,
					});
					uni.request({
						url: getApp().globalData.serverAddress + this.$uri.Uri_updateEquipment.replace(
								"{userRealId}", this.userInfo.userRealId)
							.replace("{equipmentRealId}", this.equipmentRealId),
						data: JSON.stringify(equipmentUpdateDto),
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.data.code == 0) {
								this.$utils.showToast(this, '修改成功！', 'success', 1,
									'/pages/equipments/equipmentList');
							} else {
								this.$utils.showToast(this, res.data.msg, 'error', 1, '');
							}
						},
						fail: (res) => {
							this.$utils.showToast(this, res.data.msg, 'error', 1, '');
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				}).catch(errors => {
					this.$utils.showToast(this, '请填写正确的信息！', 'warning', 1, '');
				})
			},
			onLeftClick() {
				uni.redirectTo({
					url: '/pages/equipments/equipmentList'
				})
			}
		}

	}
</script>

<style lang="scss">

</style>
